<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="username" label="员工名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="email" label="邮箱" width="150" sortable>
			</el-table-column>
			<el-table-column prop="phone" label="电话" width="120" sortable>
			</el-table-column>
			<el-table-column prop="password" label="密码" width="180" sortable>
			</el-table-column>
			<el-table-column prop="age" label="年龄" width="120" sortable>
			</el-table-column>
			<el-table-column prop="state" label="启用状态" width="100"  sortable>
				<template scope="scope"><!--scope.row可以拿到当前行的所有数据的集合-->
					<span style="color: green" v-if="scope.row.state === 1" >启用</span>
					<span style="color: red" v-else-if="scope.row.state === 0" >禁用</span>
					<span style="color: grey" v-else="scope.row.state" >未知</span>

				</template>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEmployee(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="page" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--员工编辑和修改界面-->
		<el-dialog :title="title" :visible.sync="employeeFormVisible" @close="closeDialog" :close-on-click-modal="false">
			<el-form :model="employeeForm" label-width="80px" :rules="employeeFormRules" ref="employeeForm">
				<el-form-item label="员工名称" prop="username">
					<el-input v-model="employeeForm.username" auto-complete="off"></el-input>
				</el-form-item>
               <!-- <el-form-item label="邮箱" prop="email">
                    <el-input v-model="employeeForm.email" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="employeeForm.phone" auto-complete="off"></el-input>
                </el-form-item>-->
                <el-form-item label="电话:" prop="phone" required>
                    <el-input v-model="employeeForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="Email:" prop="email" required>
                    <el-input v-model="employeeForm.email"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="employeeForm.password" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input-number v-model="employeeForm.age" :min="0" :max="200"></el-input-number>
                </el-form-item>
				<el-form-item label="员工状态">
					<el-radio-group v-model="employeeForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
                <el-form-item label="上级部门" prop="parent">
                    <el-input v-model="employeeForm.parent" auto-complete="off"></el-input>
                </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="closeForm('employeeForm')">取消</el-button>
				<el-button type="primary" @click.native="employeeSubmit" :loading="employeeLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getEmployeeListPage, removeEmployee, batchRemoveEmployee, employeeEmployee, addEmployee } from '../../api/api';

	export default {
		data() {
		    // 网上复制的邮箱和电话验证
            var checkPhone = (rule, value, callback) => {
                const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
                if (!value) {
                    return callback(new Error('电话号码不能为空'))
                }
                setTimeout(() => {
                    // Number.isInteger是es6验证数字是否为整数的方法,实际输入的数字总是识别成字符串
                    // 所以在前面加了一个+实现隐式转换

                    if (!Number.isInteger(+value)) {
                        callback(new Error('请输入数字值'))
                    } else {
                        if (phoneReg.test(value)) {
                            callback()
                        } else {
                            callback(new Error('电话号码格式不正确'))
                        }
                    }
                }, 100)
            }
            var checkEmail = (rule, value, callback) => {
                const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
                if (!value) {
                    return callback(new Error('邮箱不能为空'))
                }
                setTimeout(() => {
                    if (mailReg.test(value)) {
                        callback()
                    } else {
                        callback(new Error('请输入正确的邮箱格式'))
                    }
                }, 100)
            }
			return {
				filters: {
                    keyword: ''
				},
				employees: [],
				total: 0,
				page: 1,
                title:'',
                pageSize: 2,
				listLoading: false,
				sels: [],//列表选中列

				employeeFormVisible: false,//编辑界面是否显示
				employeeLoading: false,
				employeeFormRules: {
                    username: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					],
                    phone: [
                        {validator: checkPhone, trigger: 'blur'}
                    ],
                    email: [
                        {validator: checkEmail, trigger: 'blur'}
                    ]

                },
				//编辑界面数据
				employeeForm: {
                    id: 0,
                    username: '',
                    email: '',
                    phone: '',
                    password: '',
                    age: '',
                    state:''
				},

                employeeFormVisible: false,//新增界面是否显示
                employeeLoading: false,
                employeeFormRules: {// 新增数据校验
                    username: [// 在该输入框失去焦点时校验用户名是否输入
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					],
                    phone: [
                        {validator: checkPhone, trigger: 'blur'}
                    ],
                    email: [
                        {validator: checkEmail, trigger: 'blur'}
                    ]
				},

			}
		},
		methods: {
			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getEmployees();
			},
			//获取员工列表
			getEmployees() {
				let para = {
                    keyword: this.filters.keyword,
                    pageSize:this.pageSize,
                    currentPage:this.page
				};
				// console.log(para);
				this.listLoading = true;
				// 向后台发送请求获取值
				this.$http.post("/employee",para)
					.then(result=>{
					   	// 请求成功就从返回参数中取值赋给双向绑定的employees，而值得变动会使页面重新加载渲染
					    this.employees = result.data.list;
					    this.total = result.data.total;
					    // 关闭页面数据加载特效
                        this.listLoading = false;
					})
					.catch(result=>{
						alert("系统错误！！！");
					})

			},


			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { id: row.id };
					/*removeEmployee(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getEmployees();
					});*/
					this.$http.delete("/employee/"+para.id)
						.then(result=>{
                            if(result.data.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
							} else {
                                this.$message({
                                    message: '删除失败',
                                    type: 'error'
                                });
							}
                            this.listLoading = false;// 关闭忙等框
							this.page = 1;// 重新定位到第一页
                            this.getEmployees();// 重新加载数据
						})
	                        .catch(result => { // 失败了也要定位到第一页
                            this.listLoading = false;// 关闭忙等框
                            alert(result.data.message);
                        });
				}).catch(() => {
					alert("系统错误");
				});
			},

			//显示编辑界面
			handleEmployee: function (index, row) {
                this.title = "编辑"
				this.employeeFormVisible = true;
				this.employeeForm = Object.assign({}, row);// 克隆当前行数据用于回显
			},
			//显示新增界面
            handleAdd: function () {
			    this.title = "添加"
				this.employeeFormVisible = true;
				this.employeeForm = {
                    id: null,
                    username: '',
                    email: '',
                    phone: '',
                    password: '',
                    age: '',
                    state:''
				};
			},
			//编辑
			employeeSubmit: function () {
			    // validate（）方法可以检验整个表单，可以传入两个参数：第一个是是否校验成功，第二个是未通过校验的字段。只写一个默认是是否校验成功
				this.$refs.employeeForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.employeeLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.employeeForm);
							this.$http.put("/employee",para)
                                .then(result=>{
                                    if(result.data.success){
                                        this.$message({
                                            message: '提交成功',
                                            type: 'success'
                                        });
                                    } else {
                                        this.$message({
                                            message: '提交失败',
                                            type: 'error'
                                        });
                                    }
                                    this.employeeLoading = false;
                                    this.employeeFormVisible = false;// 关闭模态框
                                    this.getEmployees();

                                })
                                .catch(result=>{

                                })
							/*para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');*/
							/*employeeEmployee(para).then((res) => {
								this.employeeLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['employeeForm'].resetFields();
								this.employeeFormVisible = false;
								this.getEmployees();
							});*/
						});
					}
				});
			},
			selsChange: function (sels) {// 每选中一行都会把该行的数据添加到sels
				this.sels = sels;
				// console.log(sels);
			},
			//批量删除
			batchRemove: function () {
                // 遍历每行数据取出id聚合为一个id的数组
                var ids = this.sels.map(item => item.id);
                // console.log(ids);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { ids: ids };
					this.$http.patch("/employee/employee",para.ids)
                        .then(result=>{
                            if(result.data.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                            } else {
                                this.$message({
                                    message: '删除失败',
                                    type: 'error'
                                });
                            }
                            this.listLoading = false;// 关闭忙等框
                            this.page = 1;// 重新定位到第一页
                            this.getEmployees();// 重新加载数据
                        })
                        .catch(result => { // 失败了也要定位到第一页
                            this.listLoading = false;// 关闭忙等框
                            alert("系统错误");
                        });

					/*batchRemoveEmployee(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getEmployees();
					});*/
				}).catch(() => {
                    this.listLoading = false;// 关闭忙等框
                    alert("系统错误");
				});
			},
            closeDialog(){
                this.$refs['employeeForm'].resetFields();
            },
            closeForm(){
                this.employeeFormVisible = false;
                this.$refs['employeeForm'].resetFields();
            },
            search(){// 解决在除首页外的页面上，高级查询无效的bug，原因是翻页后如果不跳回首页就高级查询，
                // 而后端使用了limit，会从当前页-1再*查询的条数开始查询，如果查询结果没有这么多条那么返回结果为空
                this.page = 1;
                this.getEmployees();
            }


		},
		mounted() {
			this.getEmployees();


		}
	}

</script>

<style scoped>

</style>